﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace ClassLibrary1.Utils
{
    public class IniFileUtil
    {
        [DllImport("kernel32")]                 //返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        [DllImport("kernel32")]                 //返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);

        // 配置文件名
        public static string IniFileName { get; set; } = "setting.ini";   //实例化

        /// <summary>
        /// Read
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="strDefault"></param>
        /// <returns></returns>
        public static string ReadIniData(string Section, string Key, string strDefault)
        {
            return ReadIniData(Section, Key, strDefault, System.Windows.Forms.Application.StartupPath + "\\" + IniFileName);
        }

        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
            return temp.ToString();
        }

        /// <summary>
        /// Write
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public static bool WriteIniData(string Section, string Key, string Value)
        {
            return WriteIniData(Section, Key, Value, System.Windows.Forms.Application.StartupPath + "\\" + IniFileName);
        }

        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            if (0 == WritePrivateProfileString(Section, Key, Value, iniFilePath))
            {
            return false;
            }
            else
            {
            return true;
            }
        }

    }
}
